<?php

namespace App\Http\Controllers\Admin;

use App\Helpers\Common;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Exception;

class AdminMenuController extends BaseController
{

    public function initialize(Request $request)
    {
        parent::initialize($request);

        $currentAction = \Route::currentRouteAction();
        list($controller, $method) = explode('@', $currentAction);
        //$controller = preg_replace('/.*\\\/', '', $controller);
        if ($method == 'add' || $method == 'edit') {
            $menuOptions = Common::makeTreeOptions(
                \App\Models\AdminMenu::class,
                [['status', '<>', 90]],
                ['sorting' => 'asc', 'id' => 'asc'],
                ['顶级'],
                0,
                'name'
            );

            view()->share('menuOptions', $menuOptions);
            view()->share('params', $request->all());
        }
    }

    /**
     * List
     */
    public function index(Request $request)
    {
        $className = '\\App\\Models\\' . $this->model;
        $model = new $className;

        $data = Common::getTreeList($model, [['id', '>', 0], ['status', '<>', '90']], ['id' => 'asc'], 0, 'name', 'parent_id', true);

        return view('admin/' . strtolower($this->model) . '/' . $this->indexView, [
            'datas' => $data
        ]);
    }

    /**
     * 排序
     */
    public function listOrders(Request $request, $sortField = 'sorting')
    {
        $className = '\\App\\Models\\' . $this->model;
        $model = new $className;

        DB::beginTransaction();
        try {
            $ids = $request->input('sorting_ids');
            $fields = $request->input($sortField);
            $result = true;
            foreach ($ids as $key => $id) {
                $data[$sortField] = $fields[$key];
                $res = $model->where('id', $id)->update($data);
                if ($res === false) {
                    $result = false;
                    break;
                }
            }

            if ($result === false) {
                Db::rollback();
                return response()->json([
                    'code' => 0,
                    'msg' => '排序失败'
                ]);
            }

            DB::commit();
            return response()->json([
                'code' => 1,
                'msg' => '排序成功!'
            ]);
        } catch (Exception $e) {
            Db::rollback();
            return response()->json([
                'code' => 0,
                'msg' => $e->getMessage()
            ]);
        }
    }
}
